import { useAuthStore } from '@/stores/auth'

/**
 * 检查是否有指定权限
 * @param permission 权限代码
 * @returns 是否有权限
 */
export function hasPermission(permission: string): boolean {
  const authStore = useAuthStore()
  return authStore.hasPermission(permission)
}

/**
 * 检查是否有任意一个权限
 * @param permissions 权限代码数组
 * @returns 是否有任意一个权限
 */
export function hasAnyPermission(permissions: string[]): boolean {
  const authStore = useAuthStore()
  return authStore.hasAnyPermission(permissions)
}

/**
 * 检查是否有所有权限
 * @param permissions 权限代码数组
 * @returns 是否有所有权限
 */
export function hasAllPermissions(permissions: string[]): boolean {
  const authStore = useAuthStore()
  return authStore.hasAllPermissions(permissions)
}

/**
 * 检查是否有指定角色
 * @param role 角色代码
 * @returns 是否有角色
 */
export function hasRole(role: string): boolean {
  const authStore = useAuthStore()
  return authStore.hasRole(role)
}

/**
 * 检查是否有任意一个角色
 * @param roles 角色代码数组
 * @returns 是否有任意一个角色
 */
export function hasAnyRole(roles: string[]): boolean {
  const authStore = useAuthStore()
  return authStore.hasAnyRole(roles)
}

/**
 * 权限检查的 Vue 组合式函数
 * @returns 权限相关的方法和响应式数据
 */
export function usePermission() {
  const authStore = useAuthStore()

  return {
    hasPermission: authStore.hasPermission.bind(authStore),
    hasAnyPermission: authStore.hasAnyPermission.bind(authStore),
    hasAllPermissions: authStore.hasAllPermissions.bind(authStore),
    hasRole: authStore.hasRole.bind(authStore),
    hasAnyRole: authStore.hasAnyRole.bind(authStore),
    userPermissions: authStore.userPermissions,
    userRoles: authStore.userRoles,
    isAuthenticated: authStore.isAuthenticated
  }
}

/**
 * 按钮权限高阶组件
 * @param permission 权限代码
 * @returns 权限检查函数
 */
export function withPermission(permission: string) {
  return {
    hasPermission: () => hasPermission(permission),
    hasAnyPermission: (permissions: string[]) => hasAnyPermission(permissions),
    hasAllPermissions: (permissions: string[]) => hasAllPermissions(permissions)
  }
}

/**
 * 路由权限守卫
 * @param requiredPermissions 需要的权限
 * @returns 是否有权限访问
 */
export function checkRoutePermission(requiredPermissions: string | string[]): boolean {
  if (typeof requiredPermissions === 'string') {
    return hasPermission(requiredPermissions)
  }
  return hasAnyPermission(requiredPermissions)
}
